package org.example.netty.gRPCTest;

import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;

public class GrpcServer {
    Server server;

    public static void main(String[] args) throws IOException, InterruptedException {
        GrpcServer server = new GrpcServer();
        server.start();
        server.blockUntilShutdown();
    }

    public void start() throws IOException {
        int port = 50051;
        // 创建gRPC服务,并监听50051端口,并添加gRPC服务,gRPC服务中可以添加多个
        server = ServerBuilder.forPort(port)
                .addService(new GrpcServiceImpl())
                .build()
                .start();
        // 注册关闭服务钩子,在JVM关闭时,服务会优雅的关闭,避免服务异常关闭导致数据丢失
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            GrpcServer.this.stop();
        }));
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();//等待服务关闭,否则主线程会退出,导致server无法正常关闭
        }
    }
}
